package com.sunfeng.jksj.p27;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author : 孙峰
 * @Description:  问题原先的AtomicReference  在获取值or之后再也不会改变  导致 rf.compareAndSet(or, nr) 一直为false
 * @Date : 2022/3/7  13:43
 */
public class SafeWM {
    class WMRange {
        final int upper;
        final int lower;

        WMRange(int upper, int lower) {
            this.upper = upper;
            this.lower = lower;
        }
    }

    final AtomicReference<WMRange> rf = new AtomicReference<>(new WMRange(0, 0));

    // 设置库存上线
    void setUpper(int v) {
        WMRange nr;
        WMRange or;
        //原代码在这里 //WMRange or=rf.get();
        do {
            or = rf.get();
            if (v < or.lower) {
                throw new IllegalArgumentException();
            }
            nr = new WMRange(v, or.lower);
        } while (!rf.compareAndSet(or, nr));
    }
}
